<?php
/* SVN FILE: $Id: app_helper.php 2699 2010-08-13 11:00:17Z siva_063at09 $ */
/**
 * Short description for file.
 *
 * This file is application-wide helper file. You can put all
 * application-wide helper-related methods here.
 *
 * PHP versions 4 and 5
 *
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
 * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
 * @package       cake
 * @subpackage    cake.cake
 * @since         CakePHP(tm) v 0.2.9
 * @version       $Revision: 7904 $
 * @modifiedby    $LastChangedBy: mark_story $
 * @lastmodified  $Date: 2008-12-05 22:19:43 +0530 (Fri, 05 Dec 2008) $
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */
App::import('Core', 'Helper');
/**
 * This is a placeholder class.
 * Create the same file in app/app_helper.php
 *
 * Add your application-wide methods in the class below, your helpers
 * will inherit them.
 *
 * @package       cake
 * @subpackage    cake.cake
 */
class AppHelper extends Helper
{
    function getUserAvatar($user_id, $type = '')
    {
        App::import('Model', 'User');
        $modelObj = new User();
        $user = $modelObj->find('first', array(
            'conditions' => array(
                'User.id' => $user_id,
            ) ,
            'fields' => array(
                'UserAvatar.id',
                'UserAvatar.dir',
                'UserAvatar.filename',
                'UserAvatar.height',
                'UserAvatar.width',
                'User.fb_user_id',
                'User.avatar_url',
                'User.username',
                'User.id',
            ) ,
            'recursive' => 0
        ));
        if (!empty($user['User']['avatar_url'])) {
            if ($type == 'micro_thumb' || $type == 'small_thumb') {
				$user['User']['avatar_url'] = str_replace('_normal','_mini',$user['User']['avatar_url']);
                return $this->image($user['User']['avatar_url'], array(
                    'title' => $this->cText($user['User']['username'], false) ,
                ));
            } else  if ($type == 'normal_thumb' || $type == 'medium_thumb') {
				 return $this->link($this->image($user['User']['avatar_url'], array(
                    'title' => $this->cText($user['User']['username'], false)
                )) , array(
                    'controller' => 'users',
                    'action' => 'view',
                    $user['User']['username'],
					'admin'=>false
                ) , array(
                    'escape' => false
                ));

			} else {
				$user['User']['avatar_url'] = str_replace('_normal','_bigger',$user['User']['avatar_url']);
                return $this->link($this->image($user['User']['avatar_url'], array(
                    'title' => $this->cText($user['User']['username'], false)
                )) , array(
                    'controller' => 'users',
                    'action' => 'view',
                    $user['User']['username'],
					'admin'=>false
                ) , array(
                    'escape' => false
                ));
            }
        } elseif (!empty($user['User']['fb_user_id'])) {
            if ($type == 'micro_thumb') {
                return $this->image('http://graph.facebook.com/' . $user['User']['fb_user_id'] . '/picture?type=small', array(
                    'title' => $this->cText($user['User']['username'], false) ,
                    'width' => 20,
                    'height' => 20
                ));
            }else if ($type == 'small_thumb') {
                return $this->image('http://graph.facebook.com/' . $user['User']['fb_user_id'] . '/picture?type=small', array(
                    'title' => $this->cText($user['User']['username'], false) ,
                    'width' => 31,
                    'height' => 31
                ));
            }else if ($type == 'medium_thumb') {
                return $this->image('http://graph.facebook.com/' . $user['User']['fb_user_id'] . '/picture?type=small', array(
                    'title' => $this->cText($user['User']['username'], false) ,
                    'width' => 50,
                    'height' => 50
                ));
            } else if ($type == 'normal_thumb') {
                return $this->image('http://graph.facebook.com/' . $user['User']['fb_user_id'] . '/picture?type=normal', array(
                    'title' => $this->cText($user['User']['username'], false) ,
                    'width' => 80,
                    'height' => 80
                ));
            } else {
                return $this->link($this->image('http://graph.facebook.com/' . $user['User']['fb_user_id'] . '/picture?type=large', array(
                    'title' => $this->cText($user['User']['username'], false)
                )) , array(
                    'controller' => 'users',
                    'action' => 'view',
                    $user['User']['username'],
					'admin'=>false
                ) , array(
                    'escape' => false
                ));
            }
        } else {
            return $this->link($this->showImage('UserAvatar', $user['UserAvatar'], array(
                'dimension' => $type,
                'alt' => sprintf(__l('[Image: %s]') , $this->cText($user['User']['username'], false)) ,
                'title' => $this->cText($user['User']['username'], false)
            ) , null, null, false) , array(
                'controller' => 'users',
                'action' => 'view',
                $user['User']['username'],
				'admin'=>false
            ) , array(
                'escape' => false
            ));
        }
    }

    function transactionDescription($transaction)
    {
        $deal_name = $deal_slug = $friend_link = $user_link = '';
        $user_link = $this->getUserLink($transaction['User']);
        $foreign_user_link = $pledge_user_link = $project_owner_link = $project_link = '';
        $foreign_user_link = $this->getUserLink($transaction['ForeignUser']);
        if ($transaction['Transaction']['class'] == 'User') {
            $foreign_user_link = $this->getUserLink($transaction['ForeignUser']);
            if($transaction['Transaction']['user_id'] == ConstUserIds::Admin)
            {
              $user_link = $this->getUserLink($transaction['ForeignUser']);
            }
        }
        if ($transaction['Transaction']['class'] == 'ProjectFund' || $transaction['Transaction']['class'] == 'Project') {
            $project_link = $this->getProjectLink($transaction['ProjectFund']['Project']);
            if($transaction['Transaction']['class'] == 'Project')
            {
               $project_link = $this->getProjectLink($transaction['Project']);
            }
            $pledge_user_link = $this->getUserLink($transaction['ProjectFund']['User']);
            $project_owner_link = $this->getUserLink($transaction['ProjectFund']['Project']['User']);
            if (($transaction['TransactionType']['id'] == ConstTransactionTypes::AmountFundedToOwner ||  $transaction['TransactionType']['id'] == ConstTransactionTypes::Refunded) && $transaction['Transaction']['user_id'] != ConstUserIds::Admin)
            {
               $transaction['TransactionType']['message'].= __l(' (Site fee '.Configure::read('site.currency').$transaction['ProjectFund']['site_fee'].')');
               $transaction['TransactionType']['message_for_admin'].= __l(' (Site fee '.Configure::read('site.currency').$transaction['ProjectFund']['site_fee'].')');
            }
            else
            {
              if($transaction['TransactionType']['id'] == ConstTransactionTypes::AmountFundedToOwner)
               {
                  $transaction['TransactionType']['message'].= __l(' (Funded Amount '.Configure::read('site.currency').$transaction['ProjectFund']['amount'].')');
                  $transaction['TransactionType']['message_for_admin'].= __l(' (Funded Amount '.Configure::read('site.currency').$transaction['ProjectFund']['amount'].')');
               }
               if($transaction['TransactionType']['id'] == ConstTransactionTypes::Refunded)
               {
                  $transaction['TransactionType']['message'].= __l(' (Canceled Amount '.Configure::read('site.currency').$transaction['ProjectFund']['amount'].')');
                  $transaction['TransactionType']['message_for_admin'].= __l(' (Canceled Amount '.Configure::read('site.currency').$transaction['ProjectFund']['amount'].')');
               }
            }
            if ($transaction['TransactionType']['id'] == ConstTransactionTypes::Project)
            {
               $project_owner_link = $this->getUserLink($transaction['Project']['User']);
            }
            if($transaction['ProjectFund']['Project']['project_status_id'] == ConstProjectStatus::OpenForFunding)
            {
              $fund_values = array("funded","Funded", "Fund", "fund");
              $pledge_values = array("pledged","Pledged", "Pledge","pledge");
              $transaction['TransactionType']['message'] = str_replace($fund_values, $pledge_values, $transaction['TransactionType']['message']);
              $transaction['TransactionType']['message_for_admin'] = str_replace($fund_values, $pledge_values, $transaction['TransactionType']['message_for_admin']);
            }
        }
        if (!empty($transaction['DealUser']['payment_gateway_id']) && !empty($transaction['PaymentGateway']['name'])) {
            $payment_gateway_used = $transaction['PaymentGateway']['name'];
        }
        $transactionReplace = array(
            '##AFFILIATE_USER##' => $user_link,
            '##USER_LINK##' => $user_link,
            '##USER##' => $foreign_user_link,
            '##project##' => $project_link,
            '##PLEDGE_USER##' => $pledge_user_link,
            '##PROJECT_OWNER##' => $project_owner_link
        );
        
        if ((!empty($this->request->params['prefix']) && $this->request->params['prefix'] == 'admin') && !empty($transaction['TransactionType']['message_for_admin'])) {
            return strtr($transaction['TransactionType']['message_for_admin'], $transactionReplace);
        } else {
            return strtr($transaction['TransactionType']['message'], $transactionReplace);
        }

    }
    
	function getUserLink($user_details)
    {
        if ($user_details['user_type_id'] == ConstUserTypes::Admin || $user_details['user_type_id'] == ConstUserTypes::User) {
            return $this->link($this->cText($user_details['username'],false) , array(
                'controller' => 'users',
                'action' => 'view',
                $user_details['username'],
                'admin' => false
            ) , array(
                'title' => $this->cText($user_details['username'], false) ,
                'escape' => false
            ));
        }
    }

    function getProjectLink($project_details)
    {
            return $this->link($this->cText($project_details['name'],false) , array(
                'controller' => 'projects',
                'action' => 'view',
                $project_details['slug'],
                'admin' => false
            ) , array(
                'title' => $this->cText($project_details['name'], false) ,
                'escape' => false
            ));

    }

	function getCurrUserInfo($id)
    {
        App::import('Model', 'User');
        $this->User = new User();
        $user = $this->User->find('first', array(
            'conditions' => array(
                'User.id' => $id,
            ) ,
            'fields' => array(
                'User.id',
                'User.username',
                'User.available_balance_amount',
                'User.available_wallet_amount',
            ) ,
            'recursive' => -1
        ));
        return $user;
    }
    function getLanguage()
    {
        App::import('Model', 'Translation');
        $modelObj = new Translation();
        $languages = $modelObj->find('all', array(
            'fields' => array(
                'DISTINCT(Translation.language_id)',
                'Language.name',
                'Language.iso2'
            ),
			'order' => array(
                'Language.name' => 'asc'
            ) ,
        ));
        $languageList = array();
        if (!empty($languages)) {
            foreach($languages as $language) {
                $languageList[$language['Language']['iso2']] = $language['Language']['name'];
            }
        }
        return $languageList;
    }
    function getUserUnReadMessages($user_id = null)
    {
        App::import('Model', 'Message');
        $this->Message = new Message();
        $unread_count = $this->Message->find('count', array(
            'conditions' => array(
                'Message.is_read' => '0',
                'Message.user_id' => $user_id,
                'Message.is_sender' => '0',
                'MessageContent.admin_suspend ' => 0,
                'Message.message_folder_id' => ConstMessageFolder::Inbox,
            ) ,
            'recursive' => 1
        ));
        return $unread_count;
    }
    function filterSuspiciousWords($replace = null, $filtered_words = null)
    {
        if (!empty($filtered_words)) {
            $bad_words = unserialize($filtered_words);
            foreach($bad_words as $bad_word) {
                $replace = str_replace($bad_word, "<span class='filtered'>" . $bad_word . "</span>", $replace);
            }
        }
        return $replace;
    }
    function getSuccessProject()
    {
        App::import('Model', 'Project');
        $this->Project = new Project();
        $success_project = $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id' => ConstProjectStatus::FundingClosed
            ) ,
            'recursive' => -1
        ));
        return $success_project;
    }

    function getProjectCollectedAmount($status_id = null)
    {
        $conditions = array();
        if (!is_null($status_id)) {
            $conditions['Project.project_status_id'] = $status_id;
        }
        App::import('Model', 'Project');
        $this->Project = new Project();
        $project = $this->Project->find('all', array(
            'conditions' => $conditions,
            'fields' => array(
                'Sum(Project.collected_amount) as collected_amount',
            ) ,
            'recursive' => -1
        ));
        return $project[0][0]['collected_amount'];
    }
	public function formGooglemap($projectDetails = array() , $size = '320x320')
    {
		$projectDetails = $projectDetails;
		$projectDetails = !empty($projectFund['Project']) ? $projectFund['Project'] : $projectDetails;
		if ((!(is_array($projectDetails))) || empty($projectDetails)) {
			return false;
		}
		$color_array = array(
			array(
				'A',
				'green'
			) ,
			array(
				'B',
				'orange'
			) ,
			array(
				'C',
				'blue'
			) ,
			array(
				'D',
				'yellow'
			)
		);
		$projectDetails['map_zoom_level'] =7;
		$mapurl = 'http://maps.google.com/maps/api/staticmap?center=';
		$mapcenter[] = str_replace(' ', '+', $projectDetails['latitude']) . ',' . $projectDetails['longitude'];
		$mapcenter[] = 'zoom=' . (!empty($projectDetails['map_zoom_level']) ? $projectDetails['map_zoom_level'] : Configure::read('GoogleMap.static_map_zoom_level'));
		$mapcenter[] = 'size=' . $size;
		$mapcenter[] = 'markers=color:pink|label:M|' . $projectDetails['latitude'] . ',' . $projectDetails['longitude'];
		$mapcenter[] = 'sensor=false';
		return $mapurl . implode('&amp;', $mapcenter);
    }
	function getAffiliateCount($user_id = null)
	{
        App::import('Model', 'Affiliate');
        $this->Affiliate = new Affiliate();
        $affiliate_count = $this->Affiliate->find('count', array(
            'conditions' => array(
                'Affiliate.affliate_user_id' => $user_id
            ) ,
        ));
        return $affiliate_count;
    }
    function getCity()
    {
        App::import('Model', 'City');
        $this->City = new City();
        $cities = $this->City->find('all', array(
            'conditions' => array(
                'City.is_approved' => 1
            ) ,
            'fields' => array(
                'City.id',
                'City.name',
                'City.slug',
                'City.project_count'
            ) ,
            'order' => array(
                'City.name' => 'asc'
            ) ,
            'recursive' => -1
        ));
        $cityList = array();
        if (!empty($cities)) {
            foreach($cities as $city) {
                $cityList[$city['City']['id']] = $city['City']['name'];
            }
        }
        return $cityList;
    }
}
?>